package org.smile.excel.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import org.smile.commons.StringBand;
import org.smile.dataset.ArrayRow;
import org.smile.dataset.BaseDataSet;
import org.smile.dataset.DataSet;
import org.smile.dataset.DataSetMetaData;
import org.smile.dataset.DataSetMetaDataImpl;
import org.smile.dataset.Row;

public class Select implements Statement<ResultSet>{
	//查询的列
	List<ExpressColumn> columns;
	//查询的名
	ExpressColumn tableName;
	//条件语句 
	WhereExpress where;
	//是否是查询所有列 *
	boolean isAll=false;
	
	public Select(){
		this.columns=new ArrayList<ExpressColumn>();
	}
	
	public Select(List<ExpressColumn> columns,ExpressColumn name,WhereExpress where){
		this.columns=columns;
		this.tableName=name;
		this.where=where;
	}
	
	@Override
	public ResultSet onExecute(ExcelStatement statement) throws SQLException {
		DataSet dataset=statement.connction.loadDataSet(this.tableName.expression);
		DataSetMetaData metaData;
		if(isAll){
			metaData=dataset.getMetaData();
		}else{
			String[] names=new String[this.columns.size()];
			int idx=0;
			for(ExpressColumn ec:this.columns){
				names[idx++]=ec.getColumnLabel();
			}
			metaData=new DataSetMetaDataImpl(names);
		}
		DataSet result=new BaseDataSet(metaData);
		if(this.where!=null){
			if(this.where.isConsts()&&this.where.getConstsValue()==false){
				//是常量并为false里不需要添加
			}
			while(dataset.hasNext()){
				Row row=dataset.next();
				if(where.eval(row)){
					addRow(row, metaData, result);
				}
			}
		}else{
			while(dataset.hasNext()){
				Row row=dataset.next();
				addRow(row, metaData, result);
			}
		}
		return new ExcelResultSet(tableName.expression,result);
	}
	/**
	 * 添加一行数据到结果集中
	 * @param dataSetRow
	 * @param metaData
	 * @param result 结果集
	 */
	private void addRow(Row dataSetRow,DataSetMetaData metaData,DataSet result){
		if(isAll){
			result.addRow(dataSetRow);
		}else{
			Object[] rowValue=new Object[metaData.getColumnCount()];
			int i=0;
			for(ExpressColumn ec:this.columns){
				rowValue[i++]=ec.eval(dataSetRow);
			}
			result.addRow(new ArrayRow(metaData, rowValue));
		}
	}

	public List<ExpressColumn> getColumns() {
		return columns;
	}

	public ExpressColumn getTableName() {
		return tableName;
	}

	public void setWhere(WhereExpress where) {
		this.where = where;
	}

	@Override
	public void addColumn(ExpressColumn column) {
		this.columns.add(column);
	}
	
	public void setIsAll(){
		this.isAll=true;
	}

	@Override
	public String toString() {
		StringBand sql=new StringBand("SELECT ");
		int i=0;
		for(ExpressColumn c:this.columns){
			if(i>0){
				sql.append(",");
			}
			sql.append(c.expression);
			if(c.alias!=null){
				sql.append(" AS ").append(c.alias);
			}
		}
		if(tableName!=null){
			sql.append(" FROM ").append(tableName.expression);
		}
		if(this.where!=null){
			sql.append(" WHERE ").append(this.where.expression);
		}
		return sql.toString();
	}
}
